<template>
  <div class="dashboard-container" id="category-app">
    <div class="container">
      <div class="tableBar">
        <el-button type="primary" @click="addClass('class')">+ 新增菜品分类</el-button>
        <el-button type="primary" @click="addClass('meal')">+ 新增套餐分类</el-button>
      </div>

      <el-table :data="tableData" stripe class="tableBox">
        <el-table-column prop="name" label="分类名称"></el-table-column>
        <el-table-column label="分类类型">
          <template #default="scope">
            {{ scope.row.type === '1' ? '菜品分类' : '套餐分类' }}
          </template>
        </el-table-column>
        <el-table-column label="操作时间">
          <template #default="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序"></el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template #default="scope">
            <el-button type="text" size="small" class="blueBug" @click="editHandle(scope.row)">
              修改
            </el-button>
            <el-button type="text" size="small" class="delBut non" @click="deleteHandle(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="pageList"
          :page-sizes="[10, 20, 30, 40]"
          v-model:page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          v-model:current-page="page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 弹窗 -->
    <el-dialog :title="classData.title" v-model="classData.dialogVisible" width="30%">
      <el-form label-width="100px">
        <el-form-item label="分类名称：">
          <el-input v-model="classData.name" placeholder="请输入分类名称" maxlength="14" />
        </el-form-item>
        <el-form-item label="排序：">
          <el-input v-model.number="classData.sort" type="number" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="medium" @click="classData.dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="medium" @click="submitForm()">确 定</el-button>
        <el-button
            v-if="action !== 'edit'"
            type="primary"
            size="medium"
            class="continue"
            @click="submitForm('go')"
        >保存并继续添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElDialog, ElButton } from 'element-plus'
import {
  getCategoryPage,
  addCategory,
  editCategory,
  deleteCategory
} from '@/api/category'

import {useRouter} from "vue-router";

const router = useRouter()

// 数据定义
const action = ref('')
const page = ref(1)
const pageSize = ref(10)
const counts = ref(0)
const tableData = ref([])
const type = ref('')
const classData = ref({
  title: '添加菜品分类',
  dialogVisible: false,
  categoryId: '',
  name: '',
  sort: ''
})

// 初始化数据
const init = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value
  }

  try {
    const res = await getCategoryPage(params)
    if (res.code === 1) {
      tableData.value = res.data.records || []
      counts.value = res.data.total
    } else {
      ElMessage.error(res.msg || '请求失败')
    }
  } catch (err) {
    ElMessage.error('请求出错了：' + err)
  }
}

// 添加分类
const addClass = (st) => {
  if (st === 'class') {
    classData.value.title = '新增菜品分类'
    type.value = '1'
  } else {
    classData.value.title = '新增套餐分类'
    type.value = '2'
  }
  action.value = 'add'
  classData.value.name = ''
  classData.value.sort = ''
  classData.value.dialogVisible = true
}

// 编辑分类
const editHandle = (dat) => {
  classData.value.title = '修改分类'
  action.value = 'edit'
  classData.value.name = dat.name
  classData.value.sort = dat.sort
  classData.value.id = dat.id
  classData.value.dialogVisible = true
}

// 关闭弹窗
const handleClose = () => {
  classData.value.dialogVisible = false
}

// 删除分类
const deleteHandle = async (id) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteCategory(id)
    if (res.code === 1) {
      ElMessage.success('删除成功！')
      init()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    ElMessage.error('请求出错了：' + err)
  }
}

// 提交表单
const submitForm = async (st) => {
  const data = classData.value
  const valid = data.name && data.sort !== ''

  if (!valid) {
    ElMessage.error('请输入分类名称或排序')
    return
  }

  const reg = /^\d+$/
  if (!reg.test(data.sort)) {
    ElMessage.error('排序只能输入数字类型')
    return
  }

  if (action.value === 'add') {
    const payload = { name: data.name, type: type.value, sort: data.sort }
    try {
      const res = await addCategory(payload)
      if (res.code === 1) {
        ElMessage.success('分类添加成功！')
        if (!st) {
          classData.value.dialogVisible = false
        } else {
          classData.value.name = ''
          classData.value.sort = ''
        }
        init()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (err) {
      ElMessage.error('请求出错了：' + err)
    }
  } else {
    try {
      const res = await editCategory({ id: data.id, name: data.name, sort: data.sort })
      if (res.code === 1) {
        ElMessage.success('分类修改成功！')
        classData.value.dialogVisible = false
        init()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (err) {
      ElMessage.error('请求出错了：' + err)
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  init()
}

const handleCurrentChange = (val) => {
  page.value = val
  init()
}

onMounted(() => {
  init()
})
</script>

<style scoped>
.dashboard-container .notAdmin::after {
  border: 0 !important;
}
.continue {
  margin-left: 10px;
}
</style>
